package com.zmcn.msg.business.msgOrder.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.springframework.stereotype.Component;

import com.zmcn.msg.bean.po.Msg;
import com.zmcn.msg.bean.po.MsgOrder;
import com.zmcn.msg.bean.vo.UserVO;
import com.zmcn.msg.business.msgOrder.vo.MsgOrderVO;
import com.zmcn.msg.business.msgOrder.vo.OrderGroupVO;
import com.zmcn.msg.fw.action.Page;
import com.zmcn.msg.fw.dao.BaseDao;


/**
 * 
 * 消息订单数据处理层
 * 
 * @author <b>欧建东<br/>
 *         Email:oyjd@163.com</b>
 * @version 1.0
 */
@Component
public class MsgOrderDao extends BaseDao {
	/**
	 * 获取消息订单列表数据
	 * 
	 * @param page
	 *            页面对象
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Page<MsgOrderVO> getList(Page<MsgOrderVO> page) {
		String hqlResult = "select new " + MsgOrderVO.class.getName() + MsgOrderVO.STRUCT;
		String hqlCount = "select count(msgorder)";
		StringBuffer sb = new StringBuffer();
		sb.append(" from ").append(MsgOrder.class.getName()).append(" msgorder");
		sb.append(", ").append(Msg.class.getName()).append(" msg");
		sb.append(" where 1=1");
		Map<String, String[]> paras = page.getParas();
		List<Object> ps = new ArrayList<Object>();
		for (String key : paras.keySet()) {
			if ("creator".equals(key) || "sendor".equals(key)) {
				sb.append(" and msgorder.").append(key).append(" like ?");
				ps.add("%" + paras.get(key)[0] + "%");
			}else if("content".equals(key)){
				sb.append(" and msg.").append(key).append(" like ?");
				ps.add("%" + paras.get(key)[0] + "%");
			}
		}
		sb.append(" and msgorder.msgId=msg.msgId");
		sb.append(" order by msgorder.createTime desc, msgorder.sendTime desc, msgorder.orderId desc");
		
		// do count
		Query qCount = getSession().createQuery(hqlCount + sb.toString());
		for (int i = 0; i < ps.size(); i++) {
			qCount.setParameter(i, ps.get(i));
		}
		Long count = (Long) qCount.uniqueResult();
		page.setCount(count);
		// do result
		Query q = getSession().createQuery(hqlResult + sb.toString());
		for (int i = 0; i < ps.size(); i++) {
			q.setParameter(i, ps.get(i));
		}
		q.setFirstResult(page.getFirst());
		q.setMaxResults(page.getPageSize());
		page.setResult(q.list());
		return page;
	}	
	/**
	 * <p>Title: getReceivers</p>
	 * <p>Description: TODO 根据消息订单ID批量查询接受群并组装一个MAP<key:消息订单ID, value:接受群名称></p>
	 * @param orderIds
	 * @return
	 * Map<String,String>
	 * @throws
	 * @author 谭永戈
	 * 2012-12-7 下午4:44:54
	 */
	@SuppressWarnings("unchecked")
	public Map<String, String> getReceivers(List<String> orderIds){
		StringBuffer hql = new StringBuffer();
		hql.append("select new ").append(OrderGroupVO.class.getName()).append(OrderGroupVO.STRUCT);
		hql.append(" from OrderGroup og, PhoneGroup rg where og.groupId=rg.groupId");
		hql.append(" and og.orderId in(:ids)");
		List<OrderGroupVO> result = getSession().createQuery(hql.toString()).setParameterList("ids", orderIds).list();
		Map<String, String> resultMap = new HashMap<String, String>();
		for(OrderGroupVO vo : result){
			String value = StringUtils.isNotBlank(resultMap.get(vo.getOrderId()))?(resultMap.get(vo.getOrderId())+"<br/>"+vo.getGroupName()):vo.getGroupName();
			resultMap.put(vo.getOrderId(), value);
		}
		return resultMap;
	}
	
	/**
	 * 根据ID获取消息订单对象信息
	 * 
	 * @param id
	 *            ID
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public MsgOrderVO getMsgOrderVO(String orderId) {
		MsgOrderVO result = null;
		StringBuffer sb = new StringBuffer();
		sb.append("select new ").append(MsgOrderVO.class.getName()).append(MsgOrderVO.STRUCT);
		sb.append(" from ").append(MsgOrder.class.getName()).append(" msgorder");
		sb.append(" where msgorder.orderId=?");
		Query q=this.getSession().createQuery(sb.toString());
		q.setParameter(0, orderId);
		List<MsgOrderVO> tmpList = (List<MsgOrderVO>) q.list();
		if (tmpList.size() > 0) {
			result = tmpList.get(0);
		}
		return result;
	}
	
	/**
	 * 删除消息订单
	 * 
	 * @param ids
	 *            多个ID
	 * @param user
	 *            当前用户
	 * @return
	 */
	public void remove(String[] ids, String user) {
		StringBuffer sb = new StringBuffer();
		sb.append("update ").append(MsgOrder.class.getName()).append(" msgorder set msgorder.status=1, msgorder.lastEditor=?, msgorder.lastUpdateTime=? where");
		for (int i = 0; i < ids.length; i++) {
			sb.append(0 == i ? "" : " or");
			sb.append(" msgorder.orderId=?");
		}
		Query q = getSession().createQuery(sb.toString());
		q.setParameter(0, user);
		q.setParameter(1, new Date());
		for (int i = 0; i < ids.length; i++) {
			q.setParameter(i + 2, ids[i]);
		}
		q.executeUpdate();
	}
	/**
	 * <p>Title: sendmsg</p>
	 * <p>Description: TODO 下发消息订单</p>
	 * @param orderIds
	 * @param user
	 * @return
	 * int
	 * @throws
	 * @author 谭永戈
	 * 2012-12-7 下午5:05:50
	 */
	public int sendmsg(String[] orderIds, UserVO user){
		StringBuffer sb = new StringBuffer();
		sb.append("update ").append(MsgOrder.class.getName()).append(" set sendTime=?,sendor=? where");
		for (int i = 0; i < orderIds.length; i++) {
			sb.append(0 == i ? "" : " or");
			sb.append(" orderId=?");
		}
		Query q = getSession().createQuery(sb.toString());
		q.setParameter(0, new Date());
		q.setParameter(1, user.getAccount());
		for (int i = 0; i < orderIds.length; i++) {
			q.setParameter(i + 2, orderIds[i]);
		}
		return q.executeUpdate();
	}
}
